package com.atguigu.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.exception.NoStockException;
import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.to.mq.StockDetailTo;
import com.atguigu.common.to.mq.StockLockedTo;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.atguigu.gulimall.ware.entity.WareOrderTaskEntity;
import com.atguigu.gulimall.ware.feign.OrderFeignService;
import com.atguigu.gulimall.ware.service.WareOrderTaskDetailService;
import com.atguigu.gulimall.ware.service.WareOrderTaskService;
import com.atguigu.gulimall.ware.vo.OrderItemVo;
import com.atguigu.gulimall.ware.vo.OrderVo;
import com.atguigu.gulimall.ware.vo.SkuHasStockVo;
import com.atguigu.gulimall.ware.vo.WareSkuLockVo;
import com.rabbitmq.client.Channel;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.WareSkuDao;
import com.atguigu.gulimall.ware.entity.WareSkuEntity;
import com.atguigu.gulimall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    WareOrderTaskService orderTaskService;

    @Autowired
    WareOrderTaskDetailService orderTaskDetailService;

    @Autowired
    OrderFeignService orderFeignService;


    /**
     * 商品库存锁定自动解锁场景、
     * 库存解锁的场景
     * * 1） 下订单成功
     * *         订单过期没有支付，系统自动取消
     * *         订单被用户手动取消
     * * 2）下订单成功，锁库存成功，但是之后的操作出现问题，导致创建订单回滚
     * *
     */
    @Override
    public void unlockStock(StockLockedTo to) {
        System.out.println("收到解锁库存的消息....");
        Long id = to.getId();
        StockDetailTo detail = to.getDetail();
        Long detailId = detail.getId();
        //解锁逻辑
        //   根据库存工作单详情id(detailId)去查询这个库存工作单详情
        //   有详情: 证明库存锁定成功
        //           然后去查询有没有这个库存工作单关联的订单
        //           没有这个订单： 说明订单创建失败，库存锁定成功，需要解锁
        //           有这个订单：
        //               - 订单已取消： 解锁库存
        ///              - 订单未取消： 不能解锁库存
        //
        //   没有详情： 库存锁定失败，导致订单回滚，这种情况下无需解锁
        WareOrderTaskDetailEntity byId = orderTaskDetailService.getById(detailId);
        if (byId != null) {
            //解锁
            WareOrderTaskEntity taskEntity = orderTaskService.getById(id);
            String orderSn = taskEntity.getOrderSn();
            R r = orderFeignService.getOrderStatus(orderSn);
            if (r.getCode() == 0) {
                OrderVo orderVo = r.getData(new TypeReference<OrderVo>() {
                });
                if (orderVo == null || orderVo.getStatus() == 4) {
                    //订单不存在 或者 订单已经被取消，都要解锁库存
                    if (byId.getLockStatus() == 1) {
                        unLockStock(detail.getSkuId(), detail.getWareId(), detail.getSkuNum(), detailId);
                    }
                }
            } else {
                // 第二个参数：true  队列来的消息被拒绝接受后，重新放到队列中，让别得消费者继续消费解锁
                throw new RuntimeException("远程查询订单服务失败");
            }
        } else {
            //无需解锁
        }
    }

    //订单解锁后，发送消息解锁库存
    @Transactional
    @Override
    public void unlockStock(OrderTo to) {
        String orderSn = to.getOrderSn();
        //查询一下库存工作单的解锁状态，防止重复解锁库存
        WareOrderTaskEntity orderTaskEntity = orderTaskService.getOrderTaskByOrderSn(orderSn);
        Long orderTaskEntityId = orderTaskEntity.getId();
        //按照库存工作单ID，找到所有未解锁的库存工作单详情
        List<WareOrderTaskDetailEntity> list = orderTaskDetailService.list(
                new QueryWrapper<WareOrderTaskDetailEntity>().eq("task_id", orderTaskEntityId).eq("lock_status", 1));
        if (list != null && list.size() > 0){
            for (WareOrderTaskDetailEntity item : list) {
                //Long skuId, Long wareId, Integer num, Long taskDetailId
                unLockStock(item.getSkuId(),item.getWareId(),item.getSkuNum(), item.getId());
            }
        }
    }


    /**
     * @param
     * @Description: 解锁库存
     * @author houChen
     * @date 2022/3/1 21:09
     */
    private void unLockStock(Long skuId, Long wareId, Integer num, Long taskDetailId) {
        WareSkuDao wareSkuDao = getBaseMapper();
        wareSkuDao.unLockStock(skuId, wareId, num);
        //更新库存工作单状态
        WareOrderTaskDetailEntity wareOrderTaskDetailEntity = new WareOrderTaskDetailEntity();
        wareOrderTaskDetailEntity.setId(taskDetailId);
        wareOrderTaskDetailEntity.setLockStatus(2);
        orderTaskDetailService.updateById(wareOrderTaskDetailEntity);
    }


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        /*skuId=&wareId=*/
        QueryWrapper<WareSkuEntity> queryWrapper = new QueryWrapper<>();
        String skuId = (String) params.get("skuId");
        if (StringUtils.isNotBlank(skuId)) {
            queryWrapper.eq("sku_id", skuId);
        }
        String wareId = (String) params.get("wareId");
        if (StringUtils.isNotBlank(wareId)) {
            queryWrapper.eq("ware_id", wareId);
        }
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }


    @Override
    public List<SkuHasStockVo> getSkuHasStock(List<Long> skuIds) {
        List<SkuHasStockVo> collect = skuIds.stream().map(item -> {
            SkuHasStockVo vo = new SkuHasStockVo();
            Long count = this.baseMapper.getSkuStock(item);
            vo.setSkuId(item);
            vo.setHasStock(null == count ? false : count > 0);
            return vo;
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * @param vo
     * @Description: 为某个订单锁定库存
     * @author houChen
     * @date 2022/2/12 21:51
     * <p>
     * 库存解锁的场景
     * 1） 下订单成功
     * 订单过期没有支付，系统自动取消
     * 订单被用户手动取消
     * 2）下订单成功，锁库存成功，但是之后的操作出现问题，导致创建订单回滚
     */
    //默认只要是运行时异常，丢会进行回滚
    @Transactional(rollbackFor = NoStockException.class)
    @Override
    public Boolean orderLockStock(WareSkuLockVo vo) {
        /**
         *  保存库存工作单的详情，也就是哪一个sku在哪一个仓库，锁定了多少库存
         *
         *  ==> 为了在订单失效或者取消，或者保存订单错误但是错定库存成功时，可以反向补偿
         */
        WareOrderTaskEntity taskEntity = new WareOrderTaskEntity();
        taskEntity.setOrderSn(vo.getOrderSn());
        orderTaskService.save(taskEntity);

        List<OrderItemVo> locks = vo.getLocks();
        //1、找到该商品在哪些仓库具备库存
        List<SkuWareHasStock> collect = locks.stream().map(item -> {
            SkuWareHasStock stock = new SkuWareHasStock();
            Long skuId = item.getSkuId();
            stock.setSkuId(skuId);
            List<Long> wareIds = this.baseMapper.listWareIdHasSkuStock(skuId);
            stock.setWareId(wareIds);
            stock.setNum(item.getCount());
            return stock;
        }).collect(Collectors.toList());
        //2、锁定库存
        for (SkuWareHasStock hasStock : collect) {
            Boolean skuStockLockFlag = false;
            Long skuId = hasStock.getSkuId();
            List<Long> wareIds = hasStock.getWareId();
            if (wareIds == null || wareIds.size() == 0) {
                throw new NoStockException(skuId);
            }

            for (Long wareId : wareIds) {
                Long count = this.baseMapper.lockSkuStock(skuId, wareId, hasStock.getNum());
                if (count == 1) {
                    skuStockLockFlag = true;
                    // 告诉mq库存锁定成功，去触发接下来的一系列解锁逻辑
                    WareOrderTaskDetailEntity taskDetailEntity = new WareOrderTaskDetailEntity(null, skuId, "", hasStock.getNum(), taskEntity.getId(), wareId, 1);
                    orderTaskDetailService.save(taskDetailEntity);
                    //向消息队列发送消息
                    StockLockedTo stockLockedTo = new StockLockedTo();
                    stockLockedTo.setId(taskEntity.getId());
                    StockDetailTo stockDetailTo = new StockDetailTo();
                    BeanUtils.copyProperties(taskDetailEntity, stockDetailTo);
                    stockLockedTo.setDetail(stockDetailTo);
                    System.out.println("锁定库存成功，向RabbitMQ发送消息");
                    rabbitTemplate.convertAndSend("stock-event-exchange", "stock.locked", stockLockedTo);
                    break;
                } else {
                    //当前仓库锁定库存失败，重试下一个仓库
                }
            }
            if (skuStockLockFlag == false) { //当前skuId的商品所有仓库都没有锁定库存
                throw new NoStockException(skuId);
            }
            //3、
        }
        return true;
    }


    //skuId商品在哪些仓库具有库存
    @Data
    class SkuWareHasStock {
        private Long skuId;
        private List<Long> wareId;
        private Integer num;
    }


}